#!/usr/bin/env python

import os
import configparser
import tkinter as tk
import tkinter.ttk as ttk
import tkinter.messagebox
import tkinter.filedialog
import tkinter.scrolledtext
import tkinter.font

import common
import openchannel


software = {'description': '明渠流量计算', 'name': 'OpenChannel', 'version': '0.1', 'date': '2020-5-11'}


class MainWindow(tk.Tk):
    def __init__(self):
        super().__init__()
        self.data_config = {}
        self.load_config()

        self.title(f"{software['description']} {software['name']} {software['version']}")
        self.resizable(0, 0)
        self.geometry(common.center_screen(self, 640, 480))

        fm_in = ttk.Frame(self)
        fm_in.pack(side=tk.LEFT, fill=tk.Y, expand=True, anchor=tk.NW)
        fm_out = ttk.Frame(self)
        fm_out.pack(side=tk.LEFT, fill=tk.Y, expand=True, anchor=tk.NW)

        group_1 = ttk.LabelFrame(fm_in, text="1. 输入参数", width=70)
        group_1.pack(padx=10, pady=10, fill=tk.X, anchor=tk.NW)

        fm = ttk.Frame(group_1)
        fm.pack(padx=4, pady=4, anchor=tk.W)
        ttk.Label(fm, text="渠宽 B", width=16, anchor=tk.W).pack(side=tk.LEFT, padx=4, pady=0, anchor=tk.W)
        self.entry_b = ttk.Entry(fm, width=16)
        self.entry_b.insert(0, self.data_config['b'])
        self.entry_b.pack(side=tk.LEFT, padx=4, pady=0, anchor=tk.W)

        fm = ttk.Frame(group_1)
        fm.pack(padx=4, pady=4, anchor=tk.W)
        ttk.Label(fm, text="测量点离壁距离 Z", width=16, anchor=tk.W).pack(side=tk.LEFT, padx=4, pady=0, anchor=tk.W)
        self.entry_z = ttk.Entry(fm, width=16)
        self.entry_z.insert(0, self.data_config['z'])
        self.entry_z.pack(side=tk.LEFT, padx=4, pady=0, anchor=tk.W)

        fm = ttk.Frame(group_1)
        fm.pack(padx=4, pady=4, anchor=tk.W)
        ttk.Label(fm, text="测量点离渠底距离 h", width=16, anchor=tk.W).pack(side=tk.LEFT, padx=4, pady=0, anchor=tk.W)
        self.entry_h1 = ttk.Entry(fm, width=16)
        self.entry_h1.insert(0, self.data_config['h1'])
        self.entry_h1.pack(side=tk.LEFT, padx=4, pady=0, anchor=tk.W)

        fm = ttk.Frame(group_1)
        fm.pack(padx=4, pady=4, anchor=tk.W)
        ttk.Label(fm, text="液位 H", width=16, anchor=tk.W).pack(side=tk.LEFT, padx=4, pady=0, anchor=tk.W)
        self.entry_h = ttk.Entry(fm, width=16)
        self.entry_h.insert(0, self.data_config['h'])
        self.entry_h.pack(side=tk.LEFT, padx=4, pady=0, anchor=tk.W)

        fm = ttk.Frame(group_1)
        fm.pack(padx=4, pady=4, anchor=tk.W)
        ttk.Label(fm, text="测量点流速 u", width=16, anchor=tk.W).pack(side=tk.LEFT, padx=4, pady=0, anchor=tk.W)
        self.entry_u = ttk.Entry(fm, width=16)
        self.entry_u.insert(0, self.data_config['u'])
        self.entry_u.pack(side=tk.LEFT, padx=4, pady=0, anchor=tk.W)

        # 计算按钮
        fm = ttk.Frame(fm_in)
        fm.pack(padx=4, pady=4, fill=tk.X, expand=True, anchor=tk.S)

        self.button_calc = ttk.Button(fm, text=" \n计算\n", command=self.on_button_calc, width=20)
        self.button_calc.pack(side=tk.RIGHT, padx=4, pady=8, anchor=tk.E)

        # 计算结果
        group_out = ttk.LabelFrame(self, text="计算结果")
        group_out.pack(side=tk.LEFT, padx=10, pady=10, fill=tk.BOTH)

        self.text_result = tk.scrolledtext.ScrolledText(group_out)
        self.text_result.pack(padx=2, pady=2, fill=tk.BOTH, expand=True)

        # 创建菜单条
        menu_bar = tk.Menu(self)
        self.config(menu=menu_bar)

        # 添加帮助菜单
        file_menu = tk.Menu(menu_bar, tearoff=0)
        file_menu.add_command(label="关于", command=self.dlg_about)
        menu_bar.add_cascade(label="帮助", menu=file_menu)

        self.mainloop()

    def on_button_calc(self):
        try:
            b = float(self.entry_b.get())
            z = float(self.entry_z.get())
            h = float(self.entry_h.get())
            h1 = float(self.entry_h1.get())
            u = float(self.entry_u.get())

            self.store_config()  # 文件保存下来
            self.text_result.delete(1.0, tk.END)

            self.text_result.insert(tk.END, "============== 输入参数 ==============\n")
            self.text_result.insert(tk.END, f"渠宽 B：{b}\n")
            self.text_result.insert(tk.END, f"测量点离壁距离 Z：{z}\n")
            self.text_result.insert(tk.END, f"测量点离渠底距离 h：{h1}\n")
            self.text_result.insert(tk.END, f"液位 H：{h}\n")
            self.text_result.insert(tk.END, f"测量点流速 u：{u}\n")
            self.update()

            self.text_result.insert(tk.END, "============== 计算结果 ==============\n")
            result = openchannel.rectangle_channel(b=b, z=z, h=h, h1=h1, u=u)

            for key, value in result.items():
                self.text_result.insert(tk.END, f"{key}：\t{value:.4f}\n")

            self.text_result.insert(tk.END, "======================================\n")

        except ValueError as e:
            tkinter.messagebox.showwarning('数据错误', f'输入数据不能为空\n{e}')
            return
        except Warning as e:
            tkinter.messagebox.showwarning('数据错误', f'{e}')

    def dlg_about(self):
        dlg_about = tk.Toplevel(self)
        dlg_about.attributes("-toolwindow", 1)
        dlg_about.title("关于")
        dlg_about.geometry(common.center_dialog(self, 320, 192))

        fm = tk.Frame(dlg_about, background='white', width=320, height=160)
        fm.pack()
        fm_name = ttk.Frame(fm)
        fm_name.grid(column=0, row=0, sticky='NESW')
        fm_user = ttk.Frame(fm)
        fm_user.grid(column=0, row=1, sticky='NESW')

        ft = tk.font.Font(family='微软雅黑', size=20, weight=tk.font.BOLD)
        ttk.Label(fm_name, text=" ").grid(column=0, row=0, sticky='NESW')
        ttk.Label(fm_name, text=software['description'], font=ft).grid(column=0, columnspan=2, row=1, sticky='NESW')
        ttk.Label(fm_name, text=" ").grid(column=0, row=2, sticky='NESW')

        ft = tk.font.Font(family='微软雅黑', size=10, weight=tk.font.BOLD)
        ttk.Label(fm_user, text="软件名称", font=ft, width=10).grid(column=0, row=0, sticky='E')
        ttk.Label(fm_user, text="版本号", font=ft, width=10).grid(column=0, row=1, sticky='E')
        ttk.Label(fm_user, text="更新日期", font=ft, width=10).grid(column=0, row=2, sticky='E')
        ttk.Label(fm_user, text=software['name']).grid(column=1, row=0, sticky='NESW')
        ttk.Label(fm_user, text=software['version']).grid(column=1, row=1, sticky='NESW')
        ttk.Label(fm_user, text=software['date']).grid(column=1, row=2, sticky='NESW')

        dlg_about.mainloop()

    def load_config(self):
        if not os.path.exists(os.path.expanduser('~/OpenChannel')):
            os.mkdir(os.path.expanduser('~/OpenChannel'))
        config = configparser.ConfigParser()
        config.read(os.path.expanduser('~/OpenChannel/config.ini'))  # 不存在就是新建文件

        temporary = config['temporary'] if 'temporary' in config else {}
        self.data_config['b'] = temporary.get('b', '')
        self.data_config['z'] = temporary.get('z', '')
        self.data_config['h'] = temporary.get('h', '')
        self.data_config['h1'] = temporary.get('h1', '')
        self.data_config['u'] = temporary.get('u', '')

    def store_config(self):
        config = configparser.ConfigParser()
        config.read(os.path.expanduser('~/OpenChannel/config.ini'))  # 不存在就是新建文件
        if 'temporary' not in config:  # 节点不存在就添加
            config.add_section('temporary')

        config.set('temporary', "b", self.entry_b.get())
        config.set('temporary', "z", self.entry_z.get())
        config.set('temporary', "h", self.entry_h.get())
        config.set('temporary', "h1", self.entry_h1.get())
        config.set('temporary', "u", self.entry_u.get())

        config.write(open(os.path.expanduser('~/OpenChannel/config.ini'), "w"))  # 保存文件


if __name__ == '__main__':
    frame = MainWindow()
